//
//  UISearchBar+Category.m
//  OralRobot
//
//  Created by 王桂敏 on 16/5/25.
//  Copyright © 2016年 wangguimin. All rights reserved.
//

#import "UISearchBar+Category.h"

@implementation UISearchBar (Category)

+ (UISearchBar *)searchBarWithPlaceholder:(NSString *)placeholder
                                 delegate:(id<UISearchBarDelegate>)delegate
                        bookmarkImageName:(NSString *)bookmarkImageName{
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    searchBar.delegate = delegate;
    searchBar.placeholder = placeholder;
    UITextField *textfield = [searchBar valueForKey:@"_searchField"];
    [textfield setValue:font(28) forKeyPath:@"_placeholderLabel.font"];
    textfield.x = 0;
    searchBar.showsCancelButton = NO;//    默认的取消按钮是英文
    [searchBar setBackgroundColorOfTextFiled:ColorWithHexString(@"F0F0F0")];
    
    if (bookmarkImageName.length) {
        searchBar.showsBookmarkButton = YES;
        [searchBar setImage:Image(bookmarkImageName) forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
    }
    
    return searchBar;

}

- (void)setBackgroundColorOfTextFiled:(UIColor *)backgroundColor{
    
    UIView *searchTextField = nil;
    if (isIOS7) {
        // 经测试, 需要设置barTintColor后, 才能拿到UISearchBarTextField对象
        self.barTintColor = [UIColor whiteColor];
        searchTextField = [[[self.subviews firstObject] subviews] lastObject];
        NSLog(@"%@",[[[[self.subviews firstObject] subviews] lastObject] subviews]);
    } else {
        // iOS6以下版本searchBar内部子视图的结构不一样
        for (UIView *subView in self.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                searchTextField = subView;
            }
            
        }
    }
    
    searchTextField.backgroundColor = backgroundColor;
//    searchTextField.layer.masksToBounds = YES;
//    searchTextField.layer.cornerRadius = 5;
//    searchTextField.layer.borderColor = ColorWithHexString(@"e0e0e0").CGColor;
//    searchTextField.layer.borderWidth = 0.5;
}

@end
